package cn.xaut.剑指offer.m01;

public class demo03 {

    // 21. 合并两个有序链表
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;

        ListNode dummyHead = null;
        dummyHead.next = (l1.val < l2.val) ? l1 : l2;
        if (l1.val < l2.val) {
            dummyHead.next = l1;
            l1 = l1.next;
        } else {
            dummyHead.next = l2;
            l2 = l2.next;
        }
        dummyHead = dummyHead.next;

        return null;
    }


    // 迭代解法
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {

        ListNode dummyHead = new ListNode(-1);
        ListNode prev = dummyHead;
        while (l1 != null && l2 != null) {

            if (l1.val < l2.val) {
                prev.next = l1;
                l1 = l1.next;
            } else {
                prev.next = l2;
                l2 = l2.next;
            }
            prev = prev.next;
        }
        prev.next = (l1 == null) ? l2 : l1;

        return dummyHead.next;
    }


    // 迭代解法--------待研究
    public ListNode mergeTwoLists3(ListNode l1, ListNode l2) {

        if (l1 == null)
            return l2;
        if (l2 == null)
            return l1;
        if (l1.val < l2.val) {
            l1.next = mergeTwoLists3(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists3(l1, l2.next);
            return l2;
        }
    }
}
